package com.yingpai.fitness.dvp_2_0.main.activity.mine.address;

import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.yingpai.fitness.R;
import com.yingpai.fitness.dvp_2_0.common.activity.CommonActivity;
import com.yingpai.fitness.dvp_2_0.common.adapter.BaseAdapterHelper;
import com.yingpai.fitness.dvp_2_0.common.adapter.QuickAdapter;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.callback.Callback;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.request.RequestType;
import com.yingpai.fitness.dvp_2_0.common.util.GsonUtil;
import com.yingpai.fitness.dvp_2_0.common.util.SharedPreferencesHelp;
import com.yingpai.fitness.dvp_2_0.common.util.constant.Contacts;
import com.yingpai.fitness.dvp_2_0.main.util.DialogUtil;
import com.yingpai.fitness.dvp_2_0.main.util.ReadJsonFileUtil;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Constant;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Url;
import com.yingpai.fitness.entity.address.AddAddressBean;
import com.yingpai.fitness.entity.address.AddressBean;
import com.yingpai.fitness.entity.wx.TokenBean;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.addapp.pickers.entity.City;
import cn.addapp.pickers.entity.County;
import cn.addapp.pickers.entity.Province;

/**
 * Created by ASUS on 2018/11/22.
 */

public class AddAddressActivity extends CommonActivity {
    @BindView(R.id.right_tv)
    TextView right_tv;
    @BindView(R.id.name)
    EditText name;
    @BindView(R.id.phone)
    EditText phone;
    @BindView(R.id.address)
    TextView address;
    @BindView(R.id.address_detail)
    EditText addressDetail;
    @BindView(R.id.set_default)
    CheckBox setDefault;
    private AddressBean.MapBean.AddressesBean addressesBean;
    private int status;
    private LinearLayout province_ll;
    private LinearLayout city_ll;
    private LinearLayout area_ll;
    private TextView province;
    private TextView city;
    private TextView area;
    private View province_line;
    private View city_line;
    private View area_line;
    private ListView listView;
    private QuickAdapter<Province> provinceQuickAdapter;
    private QuickAdapter<City> cityQuickAdapter;
    private QuickAdapter<County> countyQuickAdapter;
    private int tag;
    private List<Province> data;
    private int provicePosition = 0;
    private int cityPosition = 0;
    private int arePosition = 0;
    private TokenBean tokenBean;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStatusFlag(Contacts.NORMAL_STATUS);
        setContentView(R.layout.dvp_2_0_activity_add_address);
    }

    @Override
    protected void initView() {
        setTitle("添加新地址");
        right_tv.setText("保存");
        tokenBean = (TokenBean) SharedPreferencesHelp.getBean(Constant.TOKENBEAN);
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            addressesBean = (AddressBean.MapBean.AddressesBean) bundle.getSerializable("edit_address");
            if (addressesBean != null) {
                setTitle("修改地址");
                name.setText(addressesBean.getReceiverName());
                phone.setText(addressesBean.getReceiverPhoneNo());
                address.setText(addressesBean.getAddress().split(" ")[0]);
                addressDetail.setText(addressesBean.getAddress().split(" ")[1]);
                status = Integer.parseInt(addressesBean.getStatus());
                if (Constant.REQUEST_SUCCESS_0.equals(addressesBean.getStatus())) {
                    setDefault.setChecked(false);
                } else {
                    setDefault.setChecked(true);
                }
            }
        }
    }

    @Override
    protected void initData() {

    }

    @Override
    @OnClick({R.id.address, R.id.set_default, R.id.right_tv})
    public void onViewClicked(View view) {
        super.onViewClicked(view);
        switch (view.getId()) {
            case R.id.address:
                showDialog(this, null);
                provicePosition = 0;
                cityPosition = 0;
                arePosition = 0;
                data = new ArrayList<>();
                try {
                    String json = ReadJsonFileUtil.toString(getAssets().open("address.json"));
                    data.addAll(GsonUtil.jsonToList(json, Province.class));
                } catch (IOException e) {
                    e.printStackTrace();
                }
                DialogUtil.getInstance().showBottomDialog(this, R.layout.dialog_address_select);
                View layout = DialogUtil.getInstance().dialog_bottom_layout;
                layout.findViewById(R.id.close).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        DialogUtil.getInstance().dialog_bottom.dismiss();
                    }
                });
                province_ll = layout.findViewById(R.id.province_ll);
                city_ll = layout.findViewById(R.id.city_ll);
                area_ll = layout.findViewById(R.id.area_ll);

                province = layout.findViewById(R.id.province);
                city = layout.findViewById(R.id.city);
                area = layout.findViewById(R.id.area);

                province_line = layout.findViewById(R.id.province_line);
                city_line = layout.findViewById(R.id.city_line);
                area_line = layout.findViewById(R.id.area_line);

                listView = layout.findViewById(R.id.listview);

                tag = 0;
                province.setText(data.get(0).getAreaName());

                provinceQuickAdapter = new QuickAdapter<Province>(this, R.layout.item_string) {
                    @Override
                    protected void convert(BaseAdapterHelper helper, Province item) {
                        TextView content = helper.getView(R.id.content);
                        content.setText(item.getAreaName());
                        if (helper.getPosition() == provicePosition) {
                            content.setTextColor(getResources().getColor(R.color.common_color));
                        } else {
                            content.setTextColor(Color.parseColor("#666666"));
                        }
                    }
                };

                listView.setAdapter(provinceQuickAdapter);

                provinceQuickAdapter.clear();
                provinceQuickAdapter.addAll(data);
                provinceQuickAdapter.notifyDataSetChanged();

                cityQuickAdapter = new QuickAdapter<City>(this, R.layout.item_string) {
                    @Override
                    protected void convert(BaseAdapterHelper helper, City item) {
                        TextView content = helper.getView(R.id.content);
                        content.setText(item.getAreaName());
                        if (helper.getPosition() == cityPosition) {
                            content.setTextColor(getResources().getColor(R.color.common_color));
                        } else {
                            content.setTextColor(Color.parseColor("#666666"));
                        }
                    }
                };

                countyQuickAdapter = new QuickAdapter<County>(this, R.layout.item_string) {
                    @Override
                    protected void convert(BaseAdapterHelper helper, County item) {
                        TextView content = helper.getView(R.id.content);
                        content.setText(item.getAreaName());
                        if (helper.getPosition() == arePosition) {
                            content.setTextColor(getResources().getColor(R.color.common_color));
                        } else {
                            content.setTextColor(Color.parseColor("#666666"));
                        }
                    }
                };

                listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        if (tag == 0) {
                            province.setText(provinceQuickAdapter.getItem(position).getAreaName());
                            province_line.setVisibility(View.INVISIBLE);
                            city_line.setVisibility(View.VISIBLE);
                            area_line.setVisibility(View.INVISIBLE);
                            provicePosition = position;
                            cityPosition = 0;
                            tag = 1;
                            city.setText(data.get(position).getCities().get(0).getAreaName());
                            for (int i = 0; i < data.get(position).getCities().size(); i++) {
                                if (data.get(position).getCities().get(i).getAreaId().substring(0, 2).equals(provinceQuickAdapter.getItem(position).getAreaId().substring(0, 2))) {
                                    listView.setAdapter(null);
                                    listView.setAdapter(cityQuickAdapter);
                                    cityQuickAdapter.clear();
                                    cityQuickAdapter.addAll(data.get(position).getCities());
                                    cityQuickAdapter.notifyDataSetChanged();
                                    return;
                                }
                            }

                        } else if (tag == 1) {
                            city.setText(cityQuickAdapter.getItem(position).getAreaName());
                            province_line.setVisibility(View.INVISIBLE);
                            city_line.setVisibility(View.INVISIBLE);
                            area_line.setVisibility(View.VISIBLE);
                            cityPosition = position;
                            arePosition = 0;
                            tag = 2;
                            area.setText(data.get(provicePosition).getCities().get(position).getCounties().get(0).getAreaName());
                            if (data.get(provicePosition).getCities().size() != 1) {
                                for (int i = 0; i < data.get(provicePosition).getCities().get(position).getCounties().size(); i++) {
                                    if (data.get(provicePosition).getCities().get(position).getCounties().get(i).getAreaId().substring(0, 4).equals(cityQuickAdapter.getItem(position).getAreaId().substring(0, 4))) {
                                        listView.setAdapter(null);
                                        listView.setAdapter(countyQuickAdapter);
                                        countyQuickAdapter.clear();
                                        countyQuickAdapter.addAll(data.get(provicePosition).getCities().get(position).getCounties());
                                        countyQuickAdapter.notifyDataSetChanged();
                                        return;
                                    }
                                }
                            } else {
                                for (int i = 0; i < data.get(provicePosition).getCities().get(position).getCounties().size(); i++) {
                                    if (data.get(provicePosition).getCities().get(position).getCounties().get(i).getAreaId().substring(0, 2).equals(cityQuickAdapter.getItem(position).getAreaId().substring(0, 2))) {
                                        listView.setAdapter(null);
                                        listView.setAdapter(countyQuickAdapter);
                                        countyQuickAdapter.clear();
                                        countyQuickAdapter.addAll(data.get(provicePosition).getCities().get(position).getCounties());
                                        countyQuickAdapter.notifyDataSetChanged();
                                        return;
                                    }
                                }
                            }

                        } else if (tag == 2) {
                            arePosition = position;
                            area.setText(countyQuickAdapter.getItem(position).getAreaName());
                            province_line.setVisibility(View.INVISIBLE);
                            city_line.setVisibility(View.INVISIBLE);
                            area_line.setVisibility(View.VISIBLE);
                            if (data.get(provicePosition).getCities().size() == 1) {
                                address.setText(province.getText().toString() + area.getText().toString());
                            } else {
                                address.setText(province.getText().toString() + city.getText().toString() + area.getText().toString());
                            }
                            DialogUtil.getInstance().dialog_bottom.dismiss();
                        }

                    }
                });

                province_ll.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (!city.getText().toString().equals("城市")) {
                            tag = 0;
                            province_line.setVisibility(View.VISIBLE);
                            city_line.setVisibility(View.INVISIBLE);
                            area_line.setVisibility(View.INVISIBLE);
                            listView.setAdapter(null);
                            listView.setAdapter(provinceQuickAdapter);
                            provinceQuickAdapter.clear();
                            provinceQuickAdapter.addAll(data);
                            provinceQuickAdapter.notifyDataSetChanged();
                            listView.setSelection(provicePosition);
                        }

                    }
                });
                city_ll.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (!city.getText().toString().equals("城市")) {
                            tag = 1;
                            province_line.setVisibility(View.INVISIBLE);
                            city_line.setVisibility(View.VISIBLE);
                            area_line.setVisibility(View.INVISIBLE);
                            listView.setAdapter(null);
                            listView.setAdapter(cityQuickAdapter);
                            cityQuickAdapter.clear();
                            cityQuickAdapter.addAll(data.get(provicePosition).getCities());
                            cityQuickAdapter.notifyDataSetChanged();
                            listView.setSelection(cityPosition);
                        }
                    }
                });
                area_ll.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (!city.getText().toString().equals("城市")) {
                            tag = 2;
                            province_line.setVisibility(View.INVISIBLE);
                            city_line.setVisibility(View.INVISIBLE);
                            area_line.setVisibility(View.VISIBLE);
                            listView.setAdapter(null);
                            listView.setAdapter(countyQuickAdapter);
                            countyQuickAdapter.clear();
                            countyQuickAdapter.addAll(data.get(provicePosition).getCities().get(cityPosition).getCounties());
                            countyQuickAdapter.notifyDataSetChanged();
                            listView.setSelection(0);
                        }
                    }
                });

                dismissDialog();
                break;
            case R.id.set_default:
                if (setDefault.isChecked()) {
                    status = 1;
                } else {
                    status = 0;
                }
                break;
            case R.id.right_tv:
                if (!TextUtils.isEmpty(name.getText().toString().trim())) {
                    if (!TextUtils.isEmpty(phone.getText().toString().trim())) {
                        if (!TextUtils.isEmpty(address.getText().toString().trim()) && !TextUtils.isEmpty(addressDetail.getText().toString().trim())) {
                            showDialog(this, null);
                            if (addressesBean != null) {
                                HttpParams httpParams = new HttpParams();
                                httpParams.put("id", addressesBean.getId());
                                httpParams.put("customerId", tokenBean.getId());
                                httpParams.put("address", address.getText().toString().trim() + " " + addressDetail.getText().toString().trim());
                                httpParams.put("receiverName", name.getText().toString().trim());
                                httpParams.put("receiverPhoneNo", phone.getText().toString().trim());
                                httpParams.put("status", status);
                                finalOkGo.request(RequestType.POST, Contacts.HOST_SERVER + Url.UPDATA_ADDRESS, httpParams, Url.UPDATA_ADDRESS, new Callback<AddAddressBean>() {
                                    @Override
                                    public void onSuccess(AddAddressBean addAddressBean) {
                                        if (Constant.REQUEST_SUCCESS.equals(addAddressBean.getResult())) {
//                                                    EventBus.getDefault().post(addAddressBean.getMap().getAddresses());
                                            EventBus.getDefault().post(Constant.UPDATA_ADDRESS);
                                            finish();
                                        } else {
                                            showToast(addAddressBean.getMsg());
                                        }
                                        dismissDialog();
                                    }

                                    @Override
                                    public void onError(Response<String> response) {
                                        super.onError(response);
                                        dismissDialog();
                                    }
                                });
                            } else {
                                HttpParams httpParams = new HttpParams();
                                httpParams.put("customerId", tokenBean.getId());
                                httpParams.put("address", address.getText().toString().trim() + " " + addressDetail.getText().toString().trim());
                                httpParams.put("receiverName", name.getText().toString().trim());
                                httpParams.put("receiverPhoneNo", phone.getText().toString().trim());
                                httpParams.put("status", status);
                                finalOkGo.request(RequestType.POST, Contacts.HOST_SERVER + Url.ADD_ADDRESS, httpParams, Url.ADD_ADDRESS, new Callback<AddAddressBean>() {
                                    @Override
                                    public void onSuccess(AddAddressBean addAddressBean) {
                                        if (Constant.REQUEST_SUCCESS.equals(addAddressBean.getResult())) {
                                            EventBus.getDefault().post(addAddressBean.getMap().getAddresses());
                                            EventBus.getDefault().post(Constant.UPDATA_ADDRESS);
                                            finish();
                                        } else {
                                            showToast(addAddressBean.getMsg());
                                        }
                                        dismissDialog();
                                    }

                                    @Override
                                    public void onError(Response<String> response) {
                                        super.onError(response);
                                        dismissDialog();
                                    }
                                });
                            }
                        } else {
                            showToast("地址不能为空");
                        }
                    } else {
                        showToast("电话号码不能为空");
                    }
                } else {
                    showToast("用户名不能为空");
                }
                break;
        }
    }
}
